package com.hispeed.management.filter;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Login过滤器
 *
 * @author zhangzb
 * @create 2017-06-19 11:51
 **/
public class LoginFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    private String passUrl = "";

    public void init(FilterConfig filterConfig) throws ServletException {
        passUrl = filterConfig.getInitParameter("passUrl");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        logger.info("Filter拦截请求:" + httpServletRequest.getRequestURL());
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String[] strArray = passUrl.split(";");
        for (String str : strArray) {
            if (str.equals(""))
                continue;
            if (httpServletRequest.getRequestURL().indexOf(str) >= 0) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("userinfo") != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            httpServletResponse.sendRedirect("/login.do");
        }
    }

    public void destroy() {

    }
}
